package com.zz.admin.auth.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zz.admin.userManagement.dto.UserDto;
import com.zz.common.base.dto.BaseDto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DefaultUserDetails extends BaseDto implements UserDetails {

    // 存储用户信息
    private UserDto userDto;

    // 存储权限信息（集合形式）
    private List<String> permissions;

    // 存储权限信息（字符串形式）
    private String roleAndMenu;

    //存储SpringSecurity所需要的权限信息的集合
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public DefaultUserDetails(UserDto userDto) {
        this.userDto = userDto;
    }

    public DefaultUserDetails(UserDto userDto, List<String> permissions) {
        this.userDto = userDto;
        this.permissions = permissions;
    }

    public DefaultUserDetails(UserDto userDto, String roleAndMenu) {
        this.userDto = userDto;
        this.roleAndMenu = roleAndMenu;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        if (CollectionUtils.isNotEmpty(permissions)) {
            // 把permissions中集合类型的权限信息转换成GrantedAuthority对象存入authorities中
            authorities = permissions.stream().
                    map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }else if(StringUtils.isNotBlank(roleAndMenu)) {
            // 把roleAndMenu中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(roleAndMenu);
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return userDto.getPassWord();
    }

    @Override
    public String getUsername() {
        return userDto.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return UserDetails.super.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return UserDetails.super.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return UserDetails.super.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return UserDetails.super.isEnabled();
    }
}
